package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.Base64Utils;
import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;

/**
 * Created by lenovo on 2017/7/14.
 */
@Controller
@RequestMapping("api/certified")
public class ApiCertifiedRealPersonController {
	//实人认证接口url
	//public static String url="http://172.16.3.12:18082/youtu/api/facecompare";
	//实人认证接口app_id
	public static String app_id="10087752";
	//实人认证接口session_id
	public static String session_id="6612";
	//唇语获取接口
	public static String validate_url="http://172.16.3.12:18082/youtu/openliveapi/livegetfour";
	//实人认证接口url
	public static String url="http://172.16.3.12:18082/youtu/openliveapi/livedetectfour";
	
	 @Resource
	    private WechatService wechatService;
	
	 	/**
	 	 * 跳转到视屏拍摄页面,并获取唇语验证数字
	 	 * @param request
	 	 * @param model
	 	 * @return
	 	 */
		@RequestMapping(value="srrz2")
		public String srrz2(HttpServletRequest request,Model model){
		 //Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
		 String xm=request.getParameter("xm");
		 String sfzh=request.getParameter("sfzh");
		 String source=request.getParameter("source");
		 model.addAttribute("xm",xm);
		 model.addAttribute("sfzh",sfzh);
		 //获取唇语验证数字
		 JSONObject data = new JSONObject();
			data.put("app_id", app_id);
			String s="";
			JSONObject result = new JSONObject();
			try {
				// re= JSONObject.parseObject();
				s=HttpClientUtil.post(validate_url, data);
				System.out.println(s);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(s!=null){
				JSONObject object=JSONObject.parseObject(s);
				String errorcode=object.get("errorcode").toString();
				if(errorcode.equals("0")){
					model.addAttribute("validate_data",object.get("validate_data"));
				}else{
					model.addAttribute("validate_data",object.get("errormsg"));
				}
			}
		 return "weixin/personalcenter/srrz_2";
	 }
	 /**
	  * 获取拍摄的视屏
	  * @param request
	  * @return
	  */
	@ResponseBody
	@RequestMapping(value="comparison")
	public Result comparison(HttpServletRequest request){
		//long a=System.currentTimeMillis();
		String idCard=request.getParameter("sfzh");
		String serviceId=request.getParameter("serviceId");
		String validate_data=request.getParameter("validate_data");
		String video="";
		request.getSession().setAttribute("validate_data", validate_data);
		//从微信服务器上下载视屏
		try {
			 video=getImageBase64(serviceId);
			 request.getSession().setAttribute("video", video);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Result r=new Result();
		r.setData(idCard);
		return r;
	}
	/**
	 * app上传视屏
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="appUpload")
	public Result appUpload(HttpServletRequest request){
		//long a=System.currentTimeMillis();
		String idCard=request.getParameter("sfzh");
		String validate_data=request.getParameter("validate_data");
		String video="";
		request.getSession().setAttribute("validate_data", validate_data);
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFileqztxstr =  multipartHttpServletRequest.getFile("uploadfile");
		InputStream qztxstrStream;
		try {
			qztxstrStream = multipartFileqztxstr.getInputStream();
			long qztxstrLength = multipartFileqztxstr.getSize();
			//System.out.println("qztxstrLength: "+ qztxstrLength);
			File parentFile = new File("/files/face");
			if(!parentFile.exists()){
				parentFile.mkdirs();
			}
			if(qztxstrLength>800000){
				File qztxstrFile = new File(parentFile,idCard+".mpeg");
				try {
					Thumbnails.of(qztxstrStream).scale(0.25f).toFile(qztxstrFile);
					video=Base64Utils.getBase64(qztxstrFile);
					 request.getSession().setAttribute("video", video);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}   //按照百分之15压缩
				
			}else{
				video=Base64Utils.getBase64(qztxstrStream);
				 request.getSession().setAttribute("video", video);
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Result r=new Result();
		r.setData(idCard);
		return r;
	}
	
	
	/**
	 *将身份证上传到ftp
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value = "sendSfzh")
    public void sendSfzh(HttpServletRequest request) throws Exception {
    	String sfzh=request.getParameter("sfzh");
    	String key="face:"+sfzh.toUpperCase();
    	//System.out.println("@@@@@@key:"+key);
    	if(!CacheBaseService.getInstance().exists(key)){
            String name=sfzh.toUpperCase()+".json";
            JSONObject object=new JSONObject();
            object.put("idcard", sfzh.toUpperCase());
            InputStream inStream = null;
            inStream =new ByteArrayInputStream(object.toString().getBytes());
           // System.out.println("@@@@@@key:"+key);
           // FTPUtils.getInstance().sendFile("/face/",name,inStream);
            FtpConManager.getInstance().login("172.16.1.92", "ftpup", "ftp");
            boolean flag =FtpConManager.getInstance().uploadFile(inStream, name);
            System.out.println("操作结果:"+flag);
            FtpConManager.getInstance().closeCon();
    	}
    }
	
	
	/**
	 * 获取比对接口
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="getResult")
	public String getResult(HttpServletRequest request){
		//String sfzh=request.getParameter("sfzh");
		//System.out.println("@@@@@@@@@123");
		String cardImage="";
		//获取身份证图片
				try {
					cardImage=cardImage(request.getParameter("sfzh"));
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		/**
		 * 调优图比对接口
		 */
		HttpSession session = request.getSession();
		JSONObject data = new JSONObject();
		data.put("app_id", app_id);//appid
		data.put("validate_data",session.getAttribute("validate_data").toString() );//唇语验证数据
		data.put("video",session.getAttribute("video").toString() );//视屏
		data.put("compare_flag", true);//true:返回活体检测和身份证比对结果
		data.put("card", cardImage);//身份证图片
		data.put("seq", "123");//请求序列
		data.put("card_type", 0);//card照片类型- 0代表高清 1代表带网纹照片
		String s="";
		//System.out.println(data.toString());
		JSONObject result = new JSONObject();
		try {
			// re= JSONObject.parseObject();
			s=HttpClientUtil.post(url, data);
			//long b=System.currentTimeMillis();
			//System.out.println("======优图接口比对结果"+s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return s;
	}
	
	@ResponseBody
	@RequestMapping(value="getChuyu")
	public String getChuyu(HttpServletRequest request){
		JSONObject data = new JSONObject();
		data.put("app_id", app_id);
		String s="";
		JSONObject result = new JSONObject();
		try {
			// re= JSONObject.parseObject();
			s=HttpClientUtil.post(validate_url, data);
			System.out.println(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return s;
	}
	/**
	 * 跳转到等待验证页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="srrz3")
	public String srrz3(HttpServletRequest request,Model model){
		String sfzh=request.getParameter("sfzh");
		model.addAttribute("sfzh",sfzh);
		return "weixin/personalcenter/srrz_3";
	}
	/**
	 * 跳转验证成功或验证失败页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="jump")
	public String jump(HttpServletRequest request,Model model){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		String pageName=request.getParameter("pageName");
		String msg=request.getParameter("msg");
		String sfzh=request.getParameter("sfzh");
		model.addAttribute("sfzh",sfzh);
		model.addAttribute("msg",msg);
		System.out.println("======msg"+msg);
		return "weixin/personalcenter/"+pageName;
	}
	
	/**
	 * 将实人认证通过结果传到网厅
	 */
	@RequestMapping(value="sendResultToWsbsdt")
	public Result sendResultToWsbsdt(HttpServletRequest request,Model model){
		String result=request.getParameter("result");
		String sfzh=request.getParameter("sfzh");
		Member member =(Member)request.getSession().getAttribute(Constant.SESSION_USER);
		String username=member.getLoginId();
		String url="http://172.16.1.101:8080/api/Users/UpdateSmxx?username="+username+"&smstatus="+result;
		Result re=new Result();
		try {
			 re = JSONObject.parseObject((HttpClientUtil.doGet(url)), Result.class);
			 //System.out.println("####网厅返回结果:"+re.toString());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String key="face:"+sfzh.toUpperCase();
		CacheBaseService.getInstance().delCache(key);
		return re;
	}
	
	
	
	/**
     * 从微信服务器上下载图片
     * @param serverId
     * @return
     * @throws IOException
     */
    private String getImageBase64(String serverId) throws IOException{
        InputStream is = null;
        String accessToken = WeixinUtil.getAccessTokenMer("1056");
        // 拼接请求地址
        String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", serverId);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        byte[] output = input2byte(is); //in_b为转换之后的结果
        // 根据内容类型获取扩展名
        String fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
        //this.fileExt=fileExt;
        BASE64Encoder encoder = new BASE64Encoder();
        String outstr = encoder.encode(output);
        return outstr;
    }

    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    private String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = "jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = "mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = "amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = "mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = "mp4";
        else
            fileEndWitsh = "jpg";
        return fileEndWitsh;
    }

    private byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
    
    @SuppressWarnings("unused")
	private String cardImage(String sfzh) throws Exception{
    	String name="face:"+sfzh.toUpperCase();
    	String cardImage="";
    	//JSONObject obj=CacheBaseService.getInstance().get("");
    	if(CacheBaseService.getInstance().exists(name)){
    		cardImage=CacheBaseService.getInstance().get(name);
    	}else{
    	int i = 0;
    	
        while(i<=8 ){
        	i++; //变量的值增加1
        	 cardImage=CacheBaseService.getInstance().get(name);
        	if(null!=cardImage){
        		break;
        	}
        	Thread.sleep(500);
        }}
    	return cardImage;
    }
}
